package org.itzheng.database;

import android.content.Context;

import org.itzheng.database.dao.HistoryDao;
import org.itzheng.database.dao.PlayHistoryDao;
import org.itzheng.database.dao.PlayListEntityDao;
import org.itzheng.database.entity.History;
import org.itzheng.database.entity.PlayHistory;
import org.itzheng.database.entity.PlayListEntity;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

/**
 * Title:<br>
 * Description: <br>
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2020-6-30.
 */
@Database(entities = {History.class, PlayListEntity.class, PlayHistory.class}, version = 2, exportSchema = false)
public abstract class MyDataBase extends RoomDatabase {

    public static MyDataBase getDatabase(Context context) {
//        return Room.databaseBuilder(context, MyDataBase.class, "data.db")
//                .addMigrations(DatabaseUpgrade.MIGRATION_1_2)
//                .build();
        return Room.databaseBuilder(context, MyDataBase.class, "data.db")
                .addMigrations(DatabaseUpgrade.MIGRATION_1_2)
                .build();
    }

    public abstract HistoryDao getHistoryDao();

    public abstract PlayListEntityDao getPlayListEntityDao();

    public abstract PlayHistoryDao getPlayHistoryDao();

    /**
     * 数据库升级
     */
    private static class DatabaseUpgrade {
        /**
         * 1到2，需要做什么
         */
        private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
            @Override
            public void migrate(@NonNull SupportSQLiteDatabase database) {
                // 创建新添加的表，可以将room自动生成的SQL拷贝过来
                /**
                 * {@link MyDataBase_Impl}
                 */
                database.execSQL("CREATE TABLE IF NOT EXISTS `PlayHistory` (`fPath` TEXT NOT NULL, `fTitle` INTEGER NOT NULL, `fSeek` INTEGER NOT NULL, `fDate` TEXT, PRIMARY KEY(`fPath`))");
            }
        };
    }
}
